package com.baitiaojun.xss.core.utils;

import org.jsoup.Jsoup;
import org.jsoup.nodes.Document;
import org.jsoup.safety.Whitelist;

import java.util.List;

/**
 * jsoup工具类, 用于处理xss攻击
 */
public class JsoupUtils {

    //不被过滤的html元素和属性的安全列表
    private static final Whitelist whitelist;

    //去除格式化处理
    private static final Document.OutputSettings outputSettings = new Document.OutputSettings().prettyPrint(false);

    static {
        Whitelist relaxed = Whitelist.relaxed();
        relaxed.addAttributes("all:", "style", "class"); //这里的style依然存在XSS注入风险
        relaxed.addAttributes("a", "target");
        relaxed.addAttributes("img", "src", "data"); //src支持base64编码
        whitelist = relaxed;
    }

    /**
     * jsoup过滤掉不包括在safeList中的html元素和属性, 防止XSS攻击, 防止服务端存储有XSS风险的脚本
     * @param originHtml
     * @return
     */
    public static String clean(String originHtml) {
        return Jsoup.clean(originHtml, "", whitelist, outputSettings);
    }
}
